package com.scf.fruit.configuration.web;

import com.alibaba.fastjson.JSONObject;
import com.scf.fruit.enums.ExceptionCodeEnum;
import com.scf.fruit.util.ResponseVo;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author : 孙超飞
 * @title :
 * @description :
 * @copyright :
 * @date : 2018-05-22 16:15
 */

public class LoginInterceptors extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setDateHeader("expries", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        PrintWriter out = null;

        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            LoginValid loginValid = ((HandlerMethod) handler).getMethodAnnotation(LoginValid.class);

            // 没有声明需要权限,或者声明不验证权限
            if (loginValid == null || loginValid.validate() == false) {
                return true;
            } else {
                // 在这里实现自己的权限验证逻辑

                String USERID = request.getHeader("USERID");


                if (USERID != null) {
                    return true;
                } else {
                    try {
                        out = response.getWriter();
                        ResponseVo res=new ResponseVo();
                        res.setCode(ExceptionCodeEnum.EX_NOT_PERMISSION.getValue());
                        res.setMsg(ExceptionCodeEnum.EX_NOT_PERMISSION.getMsg());
                        out.append(JSONObject.toJSONString(res));
                        return false;
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (out != null) {
                            out.close();
                        }
                    }

                }

            }
        }
        return super.preHandle(request, response, handler);
    }
}
